<?php
/**
 * Controller_Admin_Hms
 *
 * Класс Controller_Admin_Hms отвечает за обработку гостиниц в админке
 *
 * @author Дмитрий Кузьма <kouzma.d@gmail.com>
 * @version 1.0
 */
class Controller_Admin_Hms extends Controller_Base {

	protected $arrCss = array( 
		'reset.css',
		'plugins/pop_up_box.css',
	  'style.css',
	  'cms/style.css', 
	  'forms.css' 
	); //список подключаемых css-файлов,
		
	protected $arrJs = array(
	  'plugins/jquery.js',	
	  'config.js',
		'main.js',
		'plugins/JSON2.min.js',
		'plugins/pop_up_box.js',
		'plugins/jquery.auto_delete.js',
	); // список подключаемых js-файлов
	
	public function __construct(&$arrRequest) {
	  Service_Debug::setDebug();
		parent::__construct($arrRequest);
		$this->showLeftColumn = false;
		if (! SimpleAdministration::isAdmin()) $this->setError(403);
	}
	
	/**
	 * Выбор действия по URL
	 *
	 */
	public function action() {
		Service_Debug::setDebug();
		switch ($this->arrRequest[1]) {
			case '':
				$this->getIndex();
			  break;
			case 'add':
				$this->actionAdd();
			  break;
			case 'edit':
				$hotelId = intval($this->arrRequest[2]);
				$objOurHotel = new OurHotel($hotelId);
				if ($objOurHotel->id) $this->actionEdit($objOurHotel);
				else $this->setError(404);
				break;
			case 'rooms':
				$hotelId = intval($this->arrRequest[2]);
				$objOurHotel = new OurHotel($hotelId);
				if ($objOurHotel->id) $this->actionRooms($objOurHotel);
				else $this->setError(404);
				break;
			case 'prices':
				$hotelId = intval($this->arrRequest[2]);
				$objOurHotel = new OurHotel($hotelId);
				if ($objOurHotel->id) $this->actionPrices($objOurHotel);
				else $this->setError(404);
				break;
			default:
				$this->setError(404);
				break;
		}
	}

	/**
	 * Выводит список гостиниц для администрирования
	 * 
	 */
	public function getIndex() {
	  Service_Debug::setDebug();
	  $additionalConditions = " 1 ";
	  $canFindHotels = true;
	  if ($_GET) {
	  	$arrSearchParams = Service_Escape::absolutelyEscapeArray($_GET['Hotel']);
      if (!empty($arrSearchParams['country_name'])) { 
      	$countryName = $arrSearchParams['country_name'];
      	$objCountry = new Country();
      	$arrCountries = $objCountry->find('all', array('select' => '`country_code`', 'conditions' => "`country_final_name_ru` LIKE '" . $countryName . "%' OR `country_final_name_en` LIKE '" . $countryName . "%'"));
      	if (!$arrCountries) {
      		$canFindHotels = false;
      		$additionalConditions .= " AND 0";
      	}
      	else {
      		$arrCountryCodes = Service_ArrayConverter::getColumn($arrCountries, 'country_code');
      		$additionalConditions .= " AND `hotel`.`country_code` IN ('" . join("', '", $arrCountryCodes) . "')";
      	}
      }
      if (!empty($arrSearchParams['city_name']) && $canFindHotels) { // Получаем города соответствующие запросу
      	$cityName = $arrSearchParams['city_name'];
      	$objCity = new City();
      	$arrCities = $objCity->find('all', array('select' => '`ID_city`', 'conditions' => "`city_final_name_ru` LIKE '" . $cityName . "%' OR `city_final_name_en` LIKE '" . $cityName . "%' AND " . str_replace('`hotel`.', '`city`.', $additionalConditions)));
        if (!$arrCities) {
      		$canFindHotels = false;
      		$additionalConditions .= " AND 0";
      	}
      	else {
      		$arrCityIds = Service_ArrayConverter::getColumn($arrCities, 'ID_city');
      		$additionalConditions .= " AND `hotel`.`ID_city` IN ('" . join("', '", $arrCityIds) . "')";
      	}
      }
      if (!empty($arrSearchParams['hotel_name']) && $canFindHotels) {
      	$hotelName = $arrSearchParams['hotel_name'];
      	$additionalConditions .= " AND (`hotel_final_name_ru` LIKE '" . $hotelName . "%' OR `hotel_final_name_en` LIKE '" . $hotelName . "%') ";
      }
      if (!empty($arrSearchParams['not_filled']) && $canFindHotels) { 
      	$additionalConditions .= " AND `hotel`.`is_filled` = 0 ";
      } 
	  }
		$objHotel = new OurHotel();
	  $arrHotels = $objHotel->find('all', array(
	    'select' => '`our_hotel`.`hotel_final_name_ru`,`our_hotel`.`hotel_url`, `our_hotel`.`city_url`, `our_hotel`.`country_url`, `our_hotel`.`hotel_final_name_en`, `our_hotel`.`ID_our_hotel`, `our_hotel`.`ID_city`, `our_hotel`.`country_code`, `country`.`country_final_name_ru`, `country`.`country_final_name_en`, `country_admin_name_ru_2`, `country_admin_name_ru_6`, `city`.`city_final_name_ru`, `city`.`city_final_name_en`', 
	    'order' => '`hotel_final_name_ru` ASC, `hotel_final_name_en` ASC',
	    'joins' => 'LEFT JOIN `country` ON `country`.`country_code` = `our_hotel`.`country_code` LEFT JOIN `city` ON `city`.`ID_city` = `our_hotel`.`ID_city`',
	    'conditions' => $additionalConditions,
	    'limit' => $this->pageLimit, 
	    'offset' => ($this->pageNum - 1) * $this->pageLimit
	  ));
    $this->elementsInListAmount = $objHotel->count($additionalConditions); //получаем общее кол-во стран;
	  
	  $this->title = $this->pageHead = 'Администрирование гостиниц';
	  $this->addUrl = W_ABSPATH . 'hms/add/';
	  $objViewHotel = new View_Hotel();
	  $objViewAdminBlock = new View_AdminBlock();
	  $this->showHeader();
      $objViewAdminBlock->showHotelsSearchForm(new Hotel());
	    $objViewHotel->showListForAdmin($arrHotels);
     	$this->showPages();
		$this->showFooter();
	}
	
  /**
   * Выводит страницу редактирования нашей гостиницы
   * 
   * @param Hotel $objOurHotel - объект нашей гостиницы для редактирования
   */
  public function actionEdit(Hotel $objOurHotel) {
		Service_Debug::setDebug();
		$editId = $objOurHotel->id;
		$hotelName = View_Hotel::getName($objOurHotel->tableFields);
		
		if (isset($_POST['Our_Hotel'])) {
			$objOurHotel = new Hotel($_POST['Hotel']);
			if ($objOurHotel->id != $editId) User_Session::moveTo(View_Base::getLanguageUrl(W_ADMIN) . 'hotels/', Service_Translate::getText('Недопустимое действие'));
			if ($objOurHotel->save()) User_Session::moveTo(W_ADMIN . 'hotels/', 'Гостиница успешно сохранена', 1);
		}
		
  	$objViewOurHotel = new View_OurHotel();
  	
  	$this->pageHead = $this->title = 'Редактирование гостиницы "' . $hotelName . '"';
  	$this->addWysiwygMetas();
  	$this->showHeader();
  	  $objViewOurHotel->showEditHotelMenu($objOurHotel, 'edit');
      $objViewOurHotel->showEditForm($objOurHotel);
    $this->showFooter();
  }
  /**
   * Выводит страницу номеров гостиницы
   * 
   * @param OurHotel $objOurHotel - объект гостиницы номера которой рассматриваются
   */
  public function actionRooms(OurHotel $objOurHotel) {
		Service_Debug::setDebug();
    if (isset($_POST['OurRoom'])) {
  		$objOurRoom = new OurRoom($_POST['OurRoom']);
  		$objOurRoom->setField('ID_our_hotel', $objOurHotel->id);
  		if ($objOurRoom->save()) {
  			User_Session::moveTo(W_ABSPATH . 'hms/rooms/' . $objOurHotel->id . '/', 'Номер успешно добавлен', 1);
  		}
  	}
  	else {
  		$objOurRoom = new OurRoom();
  	}
		$hotelName = View_Hotel::getName($objOurHotel->tableFields);
		$objOurRoom = new OurRoom();
		$arrRooms = $objOurRoom->find('all', array('select' => '`our_room`.*, `room_type`.*', 'conditions' => "`ID_our_hotel` = '" . $objOurHotel->id . "'", 'joins' => "LEFT JOIN `room_type` USING (`ID_room_type`)"));
		$arrRoomTypes = $objOurRoom->getRoomTypes();
  	
  	$objViewOurHotel = new View_OurHotel();
  	$objViewRoom = new View_OurRoom();
  	
  	$this->pageHead = $this->title = 'Номера гостиницы "' . $hotelName . '"';
  	$this->showHeader();
  	  $objViewOurHotel->showEditHotelMenu($objOurHotel, 'rooms');
  	  $objViewRoom->showRoomsList($arrRooms);
  	  $objViewRoom->showAddForm($objOurRoom, $arrRoomTypes);
  	$this->showFooter();
  }
  /**
   * Выводит страницу номеров гостиницы
   * 
   * @param OurHotel $objOurHotel - объект гостиницы номера которой рассматриваются
   */
  public function actionPrices(OurHotel $objOurHotel) {
		Service_Debug::setDebug();

		$hotelName = View_Hotel::getName($objOurHotel->tableFields);
		$objOurRoom = new OurRoom();
		$arrRooms = $objOurRoom->find('all', array('select' => '`our_room`.*, `room_type`.*', 'conditions' => "`ID_our_hotel` = '" . $objOurHotel->id . "'", 'joins' => "LEFT JOIN `room_type` USING (`ID_room_type`)"));
		$arrPriceTypes = $objOurHotel->getPriceTypes();
  	
  	$objViewOurHotel = new View_OurHotel();
  	$objViewRoom = new View_OurRoom();
  	$objViewRoomPrice = new View_RoomPrice();
  	
  	$this->pageHead = $this->title = 'Цены номеров гостиницы "' . $hotelName . '"';
  	$this->showHeader();
  	  $objViewOurHotel->showEditHotelMenu($objOurHotel, 'prices');
  	  $objViewRoomPrice->showCalendars();
  	  $objViewRoomPrice->showNumbersMenu($arrRooms, $arrPriceTypes);
  	  echo '<div class="clear"></div>';
  	$this->showFooter();
  }
  
  /**
   * Выводит страницу добавления гостиницы
   * 
   */
  public function actionAdd() {
  	Service_Debug::setDebug();
  	if (isset($_POST['OurHotel'])) {
  		$objOurHotel = new OurHotel($_POST['OurHotel']);
  		if ($objOurHotel->save()) {
  			User_Session::moveTo(W_ABSPATH . 'hms/edit/' . $objOurHotel->id . '/', 'Гостиница успешно добавлена', 1);
  		}
  	}
  	else {
  		$objOurHotel = new OurHotel();
  	}
  	$objViewHotel = new View_OurHotel();
  	
  	$this->addCss('plugins/jquery.autocomplete.css');
  	$this->addJs('plugins/jquery.autocomplete.js');
  	$this->addJsReady("
  		options = { 
  			serviceUrl:'" . W_ABSPATH . "ajax/autosuggest/city/',
  			minChars:2,  
  			deferRequestBy: 400, 
  			onSelect: function(value, data){
  			  if (data.indexOf('/') == -1) $('#OurHotel_ID_city').val(data);
  				else document.location = W_FULLPATH + langForUrl + 'hotels/' + data + '.htm';
				} 
			};
  		var city = $('#OurHotel_city_name').autocomplete(options);
  		city.setOptions({ params: { 'action':''} });		
  	");	  
  	$this->pageHead = 'Добавление гостиницы';
  	$this->showHeader();
  	  $objViewHotel->showAddForm($objOurHotel);
  	$this->showFooter();
  }
}
?>